import createRDOM from "../template-compiler/createRDOM.js"
import diffUpdateRDOM from "../template-compiler/diffUpdateRDOM.js"
import parseTemplate from "../template-compiler/parseTemplate.js"
import replaceVariable from "../template-compiler/replaceVariable.js"
import WatchFn from "./WatchFn.js"

function createApp(options){
    const proxyData=options.setup()
    return {
        mount(root){
            this.app=document.getElementById(root)
            this.templateAst=parseTemplate(this.app.outerHTML)
            WatchFn.value=this.render.bind(this)
            this.render()
            WatchFn.value=null
        },
        render(){
            this.newAst=JSON.parse(JSON.stringify(this.templateAst))
            replaceVariable(this.newAst,proxyData)
            if(this.oldAst==null){
                // console.log("初始化")
                const RDOM=createRDOM(this.newAst)
                this.app.parentNode.replaceChild(RDOM,this.app)
                this.app=RDOM
                this.oldAst=this.newAst
                this.newAst=null
                return
            }
            // console.log("调用了diff算法")
            diffUpdateRDOM(this.oldAst,this.newAst)
        }
    }
}

export default createApp